package com.wtwd.campus.receiver;

import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.dao.CommandRecordMapper;
import com.wtwd.campus.entity.CommandRecord;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.entity.MqLockCard;
import com.wtwd.campus.entity.MqMessage;
import com.wtwd.campus.service.DeviceFlagService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.utils.ReceiverUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author mjy
 * @date 2023/02/16
 * @description
 */
@Service
@MsgType(value = Constants.GET_LOCK_CARD)
public class GetLockCardHandler implements IReceiverHandler {

    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private CommandRecordMapper commandRecordMapper;

    @Resource
    private ReceiverUtils receiverUtils;

    @Resource
    private DeviceFlagService deviceFlagService;

    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqLockCard mqLockCard = (MqLockCard) mqMessage.getObject();
        String imei = mqLockCard.getImei();
        String commandNumber = mqLockCard.getCommandNumber();
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo != null) {
            CommandRecord commandRecord = commandRecordMapper.getCommandRecordByCondition2(imei, commandNumber, Constants.GET_LOCK_CARD);
            if (commandRecord != null) {//针对于锁卡的业务处理
                deviceFlagService.updateLockCardInfo(deviceInfo.getDeviceId(), mqLockCard.getFlag(), mqLockCard.getPin(), mqLockCard.getIccid());
                //修改设备信息
                deviceInfo.setLastUpTime(System.currentTimeMillis());
                deviceInfoService.modifyDeviceInfo(deviceInfo);
                //删除缓存中的指令
                String delKey = Constants.GET_LOCK_CARD.concat("-").concat(commandNumber);
                receiverUtils.deleteCommandInRedis(imei, delKey);
                //完善指令下发记录
                receiverUtils.completeCommandRecord(Constants.GET_LOCK_CARD, imei, commandNumber, null, Constants.COMMAND_COMPLETE, new Date().getTime());
            }
        }
    }
}
